/**
 * Copyright (C), 2015-2021, XXX有限公司
 * FileName: XjfReportServiceImpl
 * Author:   Administrator
 * Date:     2021/8/12 0012 11:59
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package cn.hxlc.tie.demo.modular.jf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hxlc.tie.demo.core.consumer.NumruleServicesConsumer;
import cn.hxlc.tie.demo.core.enums.WorkOrderEnum;
import cn.hxlc.tie.demo.modular.jf.entity.*;
import cn.hxlc.tie.demo.modular.jf.mapper.XjfReportMapper;
import cn.hxlc.tie.demo.modular.jf.model.params.XjfInStoreParam;
import cn.hxlc.tie.demo.modular.jf.model.params.XjfReportParam;
import cn.hxlc.tie.demo.modular.jf.model.params.XjfWorkOrderEntryParam;
import cn.hxlc.tie.demo.modular.jf.model.result.XjfReportResult;
import cn.hxlc.tie.demo.modular.jf.model.result.XjfWorkOrderEntryResult;
import cn.hxlc.tie.demo.modular.jf.service.*;
import cn.hxlc.tie.libs.mp.page.PageFactory;
import cn.hxlc.tie.model.exp.ServiceException;
import cn.hxlc.tie.model.page.PageResult;
import cn.hxlc.tie.system.api.NumruleApi;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static cn.hxlc.tie.demo.modular.jf.controller.XjfWorkOrderController.getCurrentUserid;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author Administrator
 * @create 2021/8/12 0012
 * @since 1.0.0
 */
@Service
@Transactional
public class XjfReportServiceImpl extends ServiceImpl<XjfReportMapper, XjfReport> implements XjfReportService {

    @Autowired
    private XjfWorkOrderEntryService xjfWorkOrderEntryService;
    @Autowired
    private XjfInStoreService xjfInStoreService;
@Autowired
    NumruleApi numruleApi;
    @Autowired
    private XjfWorkOrderService xjfWorkOrderService;

    @Autowired
    private XjfReportService xjfReportService;

    @Autowired
    private XjfReqMaterialService xjfReqmaterialService;
    @Override
    public PageResult<XjfReportResult> findPageBySpec(XjfReportParam param){
        Page pageContext = getPageContext();
        IPage<XjfReportResult> page = this.baseMapper.customPageList(pageContext, param);
        return new PageResult<>(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override

    public void add(XjfReportParam param){

        XjfWorkOrderEntry xjfWorkOrderEntry = xjfWorkOrderEntryService.getById(param.getFworkorderentrtyid());

        XjfWorkOrder xjfWorkOrder = xjfWorkOrderService.getById(xjfWorkOrderEntry.getFparentid());

        if(param.getFworkorderid()==null) param.setFworkorderid(xjfWorkOrder.getFid());

        param.setFcreatorid(getCurrentUserid());

        param.setFbizdate(new Date());

        param.setFdoneqty(param.getFgoodqty().add(param.getFbadqty()));

        if(param.getFworkorderid()==null) param.setFworkorderid(xjfWorkOrder.getFid());

        if(xjfWorkOrder.getFstatus().getCode()!=2){
            throw new ServiceException(500,"" +
                    "只有下达状态的订单才可以进行汇报");
        }
        else{

        param.setFstatus(WorkOrderEnum.ZC);

        param.setFcreatetime(new Date());

        param.setFbizdate(new Date());

        XjfReport entity = getEntity(param);

        this.save(entity);
        //param.setFid(entity.getFid());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(Object[] fid) {
        XjfReport info ;
        for(int i=0;i<fid.length;i++){
            info = this.getById((Integer)fid[i]);
            if(info.getFstatus()!=null && info.getFstatus().equals(WorkOrderEnum.SH)){
                throw new ServiceException(500,"存在审核状态数据，删除失败！");
            }
            this.removeById((Integer)fid[i]);
            //distDataConsumer.distData("tie-mdm-material", DistTypeConstants.DIST_SAVE,info.getFid());
        }
    }

    private XjfReport getEntity(XjfReportParam param) {
        XjfReport entity = new XjfReport();
        BeanUtil.copyProperties(param, entity);
        return entity;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(XjfReportParam param){

        param.setFdoneqty(param.getFbadqty().add(param.getFgoodqty()));

        XjfReport oldEntity = getOldEntity(param);

        XjfReport newEntity = getEntity(param);

        newEntity.setFstatus(WorkOrderEnum.SH);
        XjfWorkOrderEntry xjfWorkOrderEntry = xjfWorkOrderEntryService.getById(param.getFworkorderentrtyid());
        xjfWorkOrderEntry.setFgoodqty(xjfWorkOrderEntry.getFgoodqty().add(param.getFgoodqty()));
        xjfWorkOrderEntry.setFbadqty(xjfWorkOrderEntry.getFbadqty().add(param.getFbadqty()));
        xjfWorkOrderEntry.setFdoneqty(param.getFdoneqty());
        xjfReportService.updateById(newEntity);
        BeanUtil.copyProperties(newEntity, oldEntity);
        this.updateById(oldEntity);
        if(xjfWorkOrderEntry.getFqty().subtract(xjfWorkOrderEntry.getFdoneqty()).intValue()<=0){
            //XjfWorkOrder xjfWorkOrder = xjfWorkOrderService.getById(param.getFworkorderid());
            PageResult<XjfReportResult> pageBySpec = xjfReportService.findPageBySpec(param);//根据ID查询到此分录的所有汇报单据
            List <XjfReportResult> rows = pageBySpec.getRows();//取得数据集
           for(int i=0;i< rows.size();i++){
               XjfReportResult xjfReportResult = rows.get(i);//取得每一条数据

               XjfReport byId = xjfReportService.getById(xjfReportResult.getFid());//取得实体类
               //XjfReqMaterial  xjfReqMaterial = xjfReqmaterialService.getById(xjfReportResult.getFworkorderid());
               byId.setFstatus(WorkOrderEnum.ZDGB);//修改状态
                this.baseMapper.updateById(byId);//保存
           }
        }
        if(xjfWorkOrderEntry.getFinstoretype().getCode()==0&&(xjfWorkOrderEntry.getFdoneqty().subtract(xjfWorkOrderEntry.getFqty()).intValue()>0)){
            //完工自动入库
            XjfInStoreParam inStoreParam = new XjfInStoreParam();
            String number = numruleApi.getNumber("cn.hxlc.tie.demo.modular.jf.model.result.XjfInStoreResult",null);
            inStoreParam.setFworkorderid(xjfWorkOrderEntry.getFparentid());
            inStoreParam.setFworkorderentrtyid(xjfWorkOrderEntry.getFid());
            inStoreParam.setFuserid(param.getFuserid());
            inStoreParam.setFstatus(WorkOrderEnum.ZC);
            inStoreParam.setFgoodqty(xjfWorkOrderEntry.getFgoodqty());
            inStoreParam.setFnumber(number);
            xjfInStoreService.add(inStoreParam);
        }
        xjfWorkOrderEntryService.updateById(xjfWorkOrderEntry);

        //redisTemplate.delete(redisTemplate.keys("getXjfWorkOrderEntrys::" + "*"));
    }

    @Override
    public XjfReportResult detail(Long fid) {
        XjfReportResult result = this.baseMapper.detail(fid);

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchChangeState(Object[] fid, WorkOrderEnum toEnum) {
        XjfReport customer ;
        XjfWorkOrder xjfWorkOrder;

        for(int i=0;i<fid.length;i++){
            customer = this.getById((Integer)fid[i]);
            xjfWorkOrder = xjfWorkOrderService.getById(customer.getFworkorderid());

            if(customer.getFstatus().getCode()>=3)
            {
                throw new ServiceException(500,"汇报单已关闭,无法进行相关操作");
            }
            if(xjfWorkOrder.getFstatus().getCode()>=3)
            {
                throw new ServiceException(500,"生产单已关闭,无法进行相关操作");
            }
            else if(customer.getFstatus()!=null && toEnum!=null && !customer.getFstatus().equals(toEnum)){

                if(toEnum.getCode()==1&&customer.getFstatus().getCode()==0) {//审核
                    customer.setFstatus(toEnum);
                    XjfWorkOrderEntry xjfWorkOrderEntry = xjfWorkOrderEntryService.getById(customer.getFworkorderentrtyid());
                    xjfWorkOrderEntry.setFgoodqty(xjfWorkOrderEntry.getFgoodqty().add(customer.getFgoodqty()));
                    xjfWorkOrderEntry.setFbadqty(xjfWorkOrderEntry.getFbadqty().add(customer.getFbadqty()));
                    xjfWorkOrderEntry.setFdoneqty(xjfWorkOrderEntry.getFdoneqty().add(customer.getFgoodqty().add(customer.getFbadqty())));
                    this.updateById(customer);
                    if(xjfWorkOrderEntry.getFqty().subtract(xjfWorkOrderEntry.getFdoneqty()).intValue()<=0){

                        XjfReportParam param = new XjfReportParam();
                        param.setFworkorderentrtyid(xjfWorkOrderEntry.getFid());
                        PageResult<XjfReportResult> pageBySpec = xjfReportService.findPageBySpec(param);
                        List <XjfReportResult> rows = pageBySpec.getRows();//取得数据集
                        for(int x=0;x< rows.size();x++){
                            XjfReportResult xjfReportResult = rows.get(x);//取得每一条数据
                            XjfReport byId = xjfReportService.getById(xjfReportResult.getFid());//取得实体类
                            byId.setFstatus(WorkOrderEnum.ZDGB);//修改状态
                            this.baseMapper.updateById(byId);//保存
                        }
                    }

                    if(xjfWorkOrderEntry.getFinstoretype().getCode()==0&&(xjfWorkOrderEntry.getFdoneqty().subtract(xjfWorkOrderEntry.getFqty()).intValue()>0)){
                        //完工自动入库
                        XjfInStoreParam inStoreParam = new XjfInStoreParam();
                        String number = numruleApi.getNumber("cn.hxlc.tie.demo.modular.jf.model.result.XjfInStoreResult",null);
                        inStoreParam.setFworkorderid(xjfWorkOrderEntry.getFparentid());
                        inStoreParam.setFworkorderentrtyid(xjfWorkOrderEntry.getFid());
                        inStoreParam.setFuserid(customer.getFuserid());
                        inStoreParam.setFstatus(WorkOrderEnum.ZC);
                        inStoreParam.setFgoodqty(BigDecimal.ZERO);
                        inStoreParam.setFnumber(number);
                        xjfInStoreService.add(inStoreParam);
                    }
                    xjfWorkOrderEntryService.updateById(xjfWorkOrderEntry);

                }
                else if(toEnum.getCode()==1&&customer.getFstatus().getCode()!=0){
                    //审核异常操作
                    throw new ServiceException(500,"只有暂存状态下的订单才可变更为审核状态");
                }

                else if(toEnum.getCode()==0&&customer.getFstatus().getCode()==1)//审核状态下的反审核
                {
                    customer.setFstatus(toEnum);
                    XjfWorkOrderEntry xjfWorkOrderEntry = xjfWorkOrderEntryService.getById(customer.getFworkorderentrtyid());
                    xjfWorkOrderEntry.setFgoodqty(xjfWorkOrderEntry.getFgoodqty().subtract(customer.getFgoodqty()));
                    xjfWorkOrderEntry.setFbadqty(xjfWorkOrderEntry.getFbadqty().subtract(customer.getFbadqty()));
                    xjfWorkOrderEntry.setFdoneqty(xjfWorkOrderEntry.getFdoneqty().subtract(customer.getFdoneqty()));
                    xjfWorkOrderEntryService.updateById(xjfWorkOrderEntry);
                    this.updateById(customer);
                }
            }
        }
    }

    private XjfReport getOldEntity(XjfReportParam param)
    {
        return this.getById(getKey(param));
    }

    private Serializable getKey(XjfReportParam param){
        return param.getFid();
    }

    private Page getPageContext() {
        return PageFactory.defaultPage();
    }
}
